package com.demo.server2.service;

import com.demo.dto.UserModifyDTO;
import com.demo.rpc.annotation.RPCTransactional;
import com.demo.server2.dao.UserDao;
import com.demo.server2.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by hunter
 *
 * @Description
 */
@Service
public class UserService {

    @Autowired
    private RpcClient rpcClient;

    @Autowired
    private UserDao userDao;

    /**
     * 普通rpc测试
     */
    public String test() {
        return "from server2 : success";
    }

    /**
     * 分布式事务测试
     *
     * @param modifyDTO
     */
    @RPCTransactional
    public void updateUser(UserModifyDTO modifyDTO) {

        User user = new User();
        user.setId(modifyDTO.getUserId());
        user.setName(modifyDTO.getName());

        userDao.save(user);

        modifyDTO.setUserId(3);
        rpcClient.testTransactional(modifyDTO);

        // 模拟业务错误, 此时本地事务回滚. server1报错不提交 server3回滚
        // throw new RuntimeException();

        // 模拟超时, 此时本地事务、server3被回滚, server1超时
        /*try {
            Thread.sleep(15 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }
}